package com.qing.demo.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author caozhipeng
 * @date 2025/7/25
 */
public class NettyClient {
    private  EventLoopGroup workerGroup = new NioEventLoopGroup();

    private Channel channel;
    public ChannelFuture connect(String host,int port){
        ChannelFuture channelFuture = null;
        try {
            Bootstrap bootstrap=new Bootstrap();
            bootstrap.group(workerGroup);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.option(ChannelOption.AUTO_READ,true);
            bootstrap.handler(new MyChannelInitializer());
            channelFuture = bootstrap.connect(host, port).syncUninterruptibly();
            this.channel=channelFuture.channel();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            if(null!=channelFuture&&channelFuture.isSuccess()){
                System.out.println("客户端链接success");
            }else{
                System.out.println("客户端链接fail");
            }
        }
        return channelFuture;
    }

    public void destroy(){
        if(null!=channel){
            channel.close();
        }
        workerGroup.shutdownGracefully();
    }
}
